package com.cloudcreativity.blyg.ui.account;

import android.app.Activity;
import android.databinding.ObservableField;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.cloudcreativity.blyg.R;
import com.cloudcreativity.blyg.base.BaseBindingRecyclerViewAdapter;
import com.cloudcreativity.blyg.base.BaseDialogImpl;
import com.cloudcreativity.blyg.base.BaseModel;
import com.cloudcreativity.blyg.databinding.ActivityDayAccountBinding;
import com.cloudcreativity.blyg.databinding.ItemLayoutDayAccountBinding;
import com.cloudcreativity.blyg.entity.Orders;
import com.cloudcreativity.blyg.entity.OrdersPage;
import com.cloudcreativity.blyg.entity.TotalAccount;
import com.cloudcreativity.blyg.utils.DefaultObserver;
import com.cloudcreativity.blyg.utils.HttpUtils;
import com.cloudcreativity.blyg.utils.MyDatePicker;
import com.cloudcreativity.blyg.utils.OrderDetailDialog;
import com.cloudcreativity.blyg.utils.SPUtils;
import com.cloudcreativity.blyg.utils.StrUtils;
import com.cloudcreativity.blyg.utils.ToastUtils;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.Calendar;
import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class DayAccountModel extends BaseModel<Activity, ActivityDayAccountBinding> {

    public ObservableField<String> date = new ObservableField<>();
    public BaseBindingRecyclerViewAdapter<Orders, ItemLayoutDayAccountBinding> adapter;

    private int currentYear;
    private int currentMonth;
    private int currentDay;

    private int pageNum;

    DayAccountModel(Activity context, ActivityDayAccountBinding binding, BaseDialogImpl baseDialog) {
        super(context, binding, baseDialog);
        Calendar instance = Calendar.getInstance(Locale.CHINESE);
        int year = instance.get(Calendar.YEAR);
        int month = instance.get(Calendar.MONTH)+1;
        int day = instance.get(Calendar.DAY_OF_MONTH);
        currentYear = year;
        currentMonth = month;
        currentDay = day;
        date.set(year+"-"+(month<10?("0"+month):month)+"-"+(day<10?("0"+day):day));
        adapter = new BaseBindingRecyclerViewAdapter<Orders, ItemLayoutDayAccountBinding>(context) {
            @Override
            protected int getLayoutResId(int viewType) {
                return R.layout.item_layout_day_account;
            }

            @Override
            protected void onBindItem(ItemLayoutDayAccountBinding binding, final Orders item, int position) {
                binding.setItem(item);
                binding.tvDetail.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new OrderDetailDialog(context,item,getBaseDialog()).show();
                    }
                });
            }
        };
        binding.rcvGoods.setLayoutManager(new LinearLayoutManager(context,
                LinearLayoutManager.VERTICAL,false));

        //加上分割线
        DividerItemDecoration itemDecoration = new DividerItemDecoration(context,DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(context.getResources().getDrawable(R.drawable.shape_item_divide));
        binding.rcvGoods.addItemDecoration(itemDecoration);

        binding.refreshDay.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                pageNum = 1;
                loadData(pageNum,currentYear,currentMonth,currentDay);
                loadTotalData(currentYear,currentMonth,currentDay);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                loadData(pageNum,currentYear,currentMonth,currentDay);
            }
        });

        binding.refreshDay.startRefresh();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    private void loadData(final int page,int year, int month, int day){
        int shopId = SPUtils.get().getUser().getShopId();
        HttpUtils.getInstance().getOrders(page, 50,shopId, year, month, day)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<OrdersPage>(getBaseDialog(),false) {
                    @Override
                    public void onSuccess(OrdersPage t) {
                        if(page==1){
                            binding.refreshDay.finishRefreshing();
                        }else{
                            binding.refreshDay.finishLoadmore();
                        }

                        if(t.getInfo().getRecords()==null|| t.getInfo().getRecords().isEmpty()){
                            //数据为空
                            if(page==1){
                                adapter.getItems().clear();
                                binding.noData.setVisibility(View.VISIBLE);
                                binding.rcvGoods.setVisibility(View.GONE);
                            }else{
                                binding.refreshDay.setEnableLoadmore(false);
                            }
                        }else{
                            //添加数据
                            if(page==1){
                                adapter.getItems().clear();
                                binding.noData.setVisibility(View.GONE);
                                binding.rcvGoods.setVisibility(View.VISIBLE);
                            }
                            adapter.getItems().addAll(t.getInfo().getRecords());

                            if(t.getInfo().getTotalpage()>page){
                                binding.refreshDay.setEnableLoadmore(true);
                                pageNum ++;
                            }else{
                                binding.refreshDay.setEnableLoadmore(false);
                            }
                        }
                    }

                    @Override
                    public void onFail(ExceptionReason msg) {
                        if(page==1){
                            binding.refreshDay.finishRefreshing();
                        }else{
                            binding.refreshDay.finishLoadmore();
                        }
                    }
                });
    }

    private void loadTotalData(int year,int month,int day){
        int shopId = SPUtils.get().getUser().getShopId();
        HttpUtils.getInstance().getTotalAccount(shopId,year,month,day)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<TotalAccount>(getBaseDialog(),false) {
                    @Override
                    public void onSuccess(TotalAccount t) {
                        binding.tvNumber.setText("订单数:"+t.getInfo().getOrderNumber());
                        binding.tvMoney.setText(String.valueOf(
                                StrUtils.get2BitDecimal(t.getInfo().getActualIncom()/100f)
                        ));
                    }
                });
    }

    @Override
    public void onBack() {
        context.finish();
    }

    public void onDateClick(){
        MyDatePicker myDatePicker = new MyDatePicker(context);
        myDatePicker.setOnChooseListener(new MyDatePicker.OnChooseListener() {
            @Override
            public void onChoose(int year, int month, int day) {
                Calendar instance = Calendar.getInstance(Locale.CHINESE);
                Calendar i2 = (Calendar) instance.clone();
                i2.set(Calendar.YEAR,year);
                i2.set(Calendar.MONTH,month);
                i2.set(Calendar.DAY_OF_MONTH,day);

                if(i2.getTimeInMillis() > instance.getTimeInMillis()) {
                    ToastUtils.showShortToast(context,"日期不能大于今天");
                }else{
                    month += 1;
                    date.set(year+"-"+(month<10?("0"+month):month)+"-"+(day<10?("0"+day):day));
                    currentYear = year;
                    currentMonth = month;
                    currentDay = day;
                    binding.refreshDay.startRefresh();
                }
            }
        });
        myDatePicker.show();
    }
}
